<template>
	<div class="main">
		<div class="scheduling_left tablelist">
			<el-select v-model="sysid" placeholder="子系统" @change="list=[];page=1;getlist();getdate()" v-if="checked"
				clearable style="margin-bottom: 10px;">
				<el-option v-for="item in options2" :key="item.id" :label="item.name" :value="item.id">
				</el-option>
			</el-select>

			<el-select v-model="typeid" placeholder="小组" @change="list=[];page=1;getlist()"
				style="margin-bottom: 10px;">
				<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
				</el-option>
			</el-select>


			<div class="userlist" ref="scrollTopList">
				<div v-if="list.length ==0" style="text-align: center;margin-top: 50px;">
					暂无工程师
				</div>
				<block v-for="item,index in list" class="tablelist">
					<div class="userli" draggable="true" @dragstart="drag($event,item.id)" @click="choseit(index)">
						<span class="uname"
							:style="act!='no'&& act == index?'font-weight: bold;font-size: 16px;':''">{{item.real_name}}</span>
						<div class="drug">
							<img :draggable="false" class="start" src="@assets/images/durg.png" alt="">
							<img :draggable="false" class="stop" src="@assets/images/delpaiban.png" alt="">
						</div>
					</div>
				</block>

			</div>


		</div>

		<div class="calender">
			<div class="calender_title">
				<div class="arrow arrow-left" @click="chooseMonth(-1)">
					<img src="@assets/images/prev.png" alt="">
				</div>
				<div class="data">{{year}}.{{month.toString().padStart(2, '0')}}</div>
				<div class="arrow arrow-right" @click="chooseMonth(1)">
					<img src="@assets/images/next.png" alt="">
				</div>
			</div>
			<div class="calender_content">
				<div class="row title">
					<span v-for="week in weeks" :key="week">{{ week }}</span>
				</div>
				<div class="row content">
					<div class="day" v-for="(day, index) in days" :key="index" @click="add(index)"
						:style="act!='no'?'cursor: pointer;':''">
						<p>{{day.gregorian}} </p>
						<span>{{day.IDayCn}}</span>
						<div class="drop" @drop="drop($event,day)" @dragover="allowDrop($event)"
							@click="unbind($event,day)">
							<div class="userli" v-if="day.userName">
								<span class="uname">{{day.userName}}</span>
								<div class="drug">
									<img :draggable="false" class="stop" src="@assets/images/delpaiban.png" alt="">
								</div>
							</div>
						</div>
					</div>

				</div>
			</div>

		</div>


		<div class="loading-content" v-if="showloading">
			<div class="loading-spinner">
				<svg viewBox="25 25 50 50" class="circular">
					<circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
				</svg>
			</div>
			<div class="loading-text">加载中...</div>
		</div>
	</div>

</template>

<script>
	import calendar from '@/utils/calendar'

	export default {
		data() {
			return {
				options2: [],
				options: [],
				sysid: '',
				sysids: '',
				value: '',
				year: 0,
				month: 0,
				today: 0,
				days: [],
				weeks: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],

				currentDay: new Date().getDate(),
				currentMonth: new Date().getMonth(),
				currentYear: new Date().getFullYear(),
				page: 1,
				limit: 30,
				showloading: false,
				checked: false,
				typeid: "",
				list: [],
				id: "",
				total: 0,
				act: 'no',
				uname: sessionStorage.getItem('uname')

			};
		},
		// components: {
		//   Draggable,
		//   Droppable
		// },
		computed: {

		},
		mounted() {
			const now = new Date()
			this.year = now.getFullYear()
			this.month = now.getMonth() + 1
			this.today = now.getDate()
			console.log(this.$refs.scrollTopList)
			this.$refs.scrollTopList.addEventListener("scroll", this.throttle(this.handleScroll, 500), true)

			this.getgroup()
			this.getopen()
			// this.getdate()
		},

		methods: {
			getSysSon() {
				var that = this
				var param = {
					userId: sessionStorage.getItem('uid')
				}
				this.$http.post(this.$url + '/sys/user/getSysSon', this.$qs.stringify(param))
					.then(function(response) {
						if (response.data.code == '1410') {
							that.$Toast(response.data.msg);
							sessionStorage.setItem('token', '')
							that.$router.push('/login')
							return
						}
						that.options2 = response.data.data
						var arr = []
						for (var i = 0; i < response.data.data.length; i++) {
							arr.push(response.data.data[i].id)
						}
						var ids = ''
						if (arr.length > 0) {
							ids = arr.join(',')
						}
						that.sysids = ids
						that.sysid = that.options2.length > 0 ? that.options2[0].id : 0

						that.getlist()
						that.getdate()
					})
					.catch(function(error) {
						console.log(error)
						that.$Toast('网络拥堵，刷新一下');
					});
			},
			getopen() {
				this.showloading = true

				var that = this
				this.$http.get(this.$url + '/moreSys/open/select')
					.then(function(response) {
						if (response.data.code == '1410') {
							that.$Toast(response.data.msg);
							sessionStorage.setItem('token', '')
							that.$router.push('/login')
							return
						}
						that.checked = response.data == 1 ? true : false
						if (that.checked) {
							that.getSysSon()
						} else {
							that.getlist()
							that.getdate()
						}
						that.showloading = false
					})
					.catch(function(error) {
						console.log(error);
						that.$Toast('网络拥堵，刷新一下');
					});

			},
			choseit(i) {
				this.act = this.act == i ? 'no' : i
			},
			add(i) {
				console.log(this.days[i])
				if (this.act != 'no') {
					this.id = this.list[this.act].id
					if (!this.days[i].cDay) {
						return
					}
					if (this.days[i].userName) {
						this.$Toast('请先解除当前日期绑定');
						return
					}
					this.bindenger(this.days[i].cYear, this.days[i].cMonth, this.days[i].cDay)
				}
			},
			handleScroll() {

				let scrollTop = this.$refs.scrollTopList.scrollTop,
					clientHeight = this.$refs.scrollTopList.clientHeight,
					scrollHeight = this.$refs.scrollTopList.scrollHeight,
					height = 50; //根据项目实际定义
				if (scrollTop + clientHeight >= scrollHeight - height) {
					if (this.page > this.total) {
						return false
					} else {
						this.page = this.page + 1 //显示条数新增
						this.getlist() //请求列表list 接口方法
					}
				} else {
					return false
				}
			},
			throttle(func, wait) {

				let lastTime = null
				let timeout
				return () => {
					let context = this;
					let now = new Date();
					let arg = arguments;
					if (now - lastTime - wait > 0) {
						if (timeout) {
							clearTimeout(timeout)
							timeout = null
						}
						func.apply(context, arg)
						lastTime = now
					} else if (!timeout) {
						timeout = setTimeout(() => {
							func.apply(context, arg)
						}, wait)
					}
				}
			},
			getdate() {
				this.showloading = true
				var id = ''
				var url = ''
				if (this.sysid) {
					id = this.sysid
					url = this.$url + '/duty/roster/work/getAll?sysSonId=' + id
				} else if (this.sysids) {
					id = this.sysids
					url = this.$url + '/duty/roster/work/getAll'
				} else {
					id = this.sysids
					url = this.$url + '/duty/roster/work/getAll'
				}
				var that = this
				this.$http.get(url)
					.then(function(response) {
						if (response.data.code == '1410') {
							that.$Toast(response.data.msg);
							sessionStorage.setItem('token', '')
							that.$router.push('/login')
							return
						}
						that.datelist = response.data.data

						that.showloading = false
						that.getDays()
					})
					.catch(function(error) {
						console.log(error);

						that.$Toast('网络拥堵，刷新一下');
					});

			},
			// 拖拽
			drag(ev, id) {
				console.log("拖动", id);
				this.id = id;
				this.dom = ev.currentTarget.cloneNode(true);
				// console.log(this.dom);
			},
			// 允许放下拖拽
			allowDrop(ev) {
				ev.preventDefault();
				// console.log(ev.srcElement.children.length)

			},
			// 放下事件
			drop(ev, item) {
				console.log(item);
				if (this.$permissions.indexOf(39) == -1) {
					this.$Toast('暂无权限');
					return
				}
				// console.log(ev);
				if (ev.srcElement.children.length == 0 && ev.srcElement.className == 'drop' && item.gregorian != '') {
					ev.preventDefault();
					let treeNode = ev.target;
					if (treeNode) {
						treeNode.appendChild(this.dom);
					}
					this.bindenger(item.cYear, item.cMonth, item.cDay)
					treeNode.removeChild(this.dom);
				}

			},
			unbind(ev, data) {
				if (this.$permissions.indexOf(40) == -1) {
					this.$Toast('暂无权限');
					return
				}
				console.log(ev.srcElement.className)
				if (ev.srcElement.className != 'stop') {
					return
				}

				this.showloading = true
				var date = ''

				let month = data.cMonth < 10 ? "0" + (data.cMonth) : data.cMonth;
				let day = data.cDay < 10 ? "0" + data.cDay : data.cDay;
				date = data.cYear + '-' + month + '-' + day
				console.log(date)

				var id = ''
				var url = ''
				var param = {}
				if (this.sysid) {
					id = this.sysid
					param = {
						date,
						sysSonId: id
					}
				} else if (this.sysids) {
					id = this.sysids
					param = {
						date,
					}
				} else {
					id = this.sysids
					param = {
						date,
					}
				}
				var that = this
				// memo/select
				this.$http.post(this.$url + '/duty/roster/work/removeDateBand', this.$qs.stringify(param))
					.then(function(response) {
						if (response.data.code == '1410') {
							that.$Toast(response.data.msg);
							sessionStorage.setItem('token', '')
							that.$router.push('/login')
							return
						}
						that.$Toast(response.data.msg);
						that.showloading = false
						that.getdate()
					})
					.catch(function(error) {
						console.log(error);
						// sessionStorage.setItem('token','undefined')
						// that.$router.push('/login')

						that.$Toast('网络拥堵，刷新一下');
					});

			},
			bindenger(cYear, cMonth, cDay) {
				if (this.$permissions.indexOf(39) == -1) {
					this.$Toast('暂无权限');
					return
				}
				this.showloading = true
				var date = ''

				let month = cMonth < 10 ? "0" + (cMonth) : cMonth;
				let day = cDay < 10 ? "0" + cDay : cDay;
				date = cYear + '-' + month + '-' + day
				console.log(typeof this.id)
				// var param = {
				// 	date,
				// 	userId: this.id,
				// }

				var that = this
				var id = ''
				var url = ''
				var param = {}
				if (this.sysid) {
					id = this.sysid
					param = {
						date,
						userId: this.id,
						sysSonId: id
					}
				} else if (this.sysids) {
					id = this.sysids
					param = {
						date,
						userId: this.id,
					}
				} else {
					param = {
						date,
						userId: this.id
					}
				}

				this.$http.post(this.$url + '/duty/roster/work/dateBand', this.$qs.stringify(param))
					.then(function(response) {
						if (response.data.code == '1410') {
							that.$Toast(response.data.msg);
							sessionStorage.setItem('token', '')
							that.$router.push('/login')
							return
						}
						that.$Toast(response.data.msg);
						that.showloading = false
						that.getdate()
					})
					.catch(function(error) {
						console.log(error);
						// sessionStorage.setItem('token','undefined')
						// that.$router.push('/login')

						that.$Toast('网络拥堵，刷新一下');
					});

			},
			getlist() {
				this.showloading = true
				var that = this
				var zuid = !this.typeid ? '' : this.typeid

				var id = ''
				var url = ''
				if (this.sysid) {
					id = this.sysid
					url = encodeURI(this.$url + '/engineer/select?page=' + this.page + '&limit=' + this.limit +
						'&userName=' + '&groupId=' + zuid + '&sysSonIds=' + id)
				} else if (this.sysids) {
					id = this.sysids
					url = encodeURI(this.$url + '/engineer/select?page=' + this.page + '&limit=' + this.limit +
						'&userName=' + '&groupId=' + zuid + '&sysSonIds=' + id)
				} else {
					url = encodeURI(this.$url + '/engineer/select?page=' + this.page + '&limit=' + this.limit +
						'&userName=' + '&groupId=' + zuid)
				}
				// var url = encodeURI(this.$url + '/engineer/select?page=' + this.page + '&limit=' + this.limit +
				// 	'&userName=' + '&groupId=' + zuid+'&sysSonIds='+id)
				this.$http.get(url)
					.then(function(response) {
						if (response.data.code == '1410') {
							that.$Toast(response.data.msg);
							sessionStorage.setItem('token', '')
							that.$router.push('/login')
							return
						}
						that.total = response.data.count
						for (var i = 0; i < response.data.data.length; i++) {
							that.list.push(response.data.data[i])
						}

						that.showloading = false
					})
					.catch(function(error) {
						console.log(error);

						that.$Toast('网络拥堵，刷新一下');
					});

			},

			// 获取分组
			getgroup() {
				this.showloading = true

				var that = this
				this.$http.get(this.$url + '/engineer/selectGroup')
					.then(function(response) {
						if (response.data.code == '1410') {
							that.$Toast(response.data.msg);
							sessionStorage.setItem('token', '')
							that.$router.push('/login')
							return
						}
						that.options = response.data.data
						that.options.unshift({
							name: '全部',
							value: 0
						})
						that.showloading = false
					})
					.catch(function(error) {
						console.log(error);

						that.$Toast('网络拥堵，刷新一下');
					});

			},
			getDays() { // 获取当前月份所有公历日期及其农历日期
				this.days = []
				const day = new Date()
				day.setFullYear(this.year, this.month - 1, 1) // 此处较之前调整，获取当月第一天
				const month = new Date()
				month.setFullYear(this.year, this.month, 0) // 此处较之前调整，获取当月
				for (let i = 0; i < day.getDay(); i++) { // 当月第一天距离所在周周一的空白占位
					this.days.push({
						gregorian: '',
						IDayCn: '',
						IMonthCn: '',
						lDay: '',
						lMonth: ''
					})
				}
				for (let i = 1; i <= month.getDate(); i++) { // 获取当月天数填充日历
					let lunarCalendar = calendar.solar2lunar(this.year, this.month, i);

					var date = ''

					let month = lunarCalendar.cMonth < 10 ? "0" + (lunarCalendar.cMonth) : lunarCalendar.cMonth;
					let day = lunarCalendar.cDay < 10 ? "0" + lunarCalendar.cDay : lunarCalendar.cDay;
					date = lunarCalendar.cYear + '-' + month + '-' + day
					var userName = ''
					for (var j = 0; j < this.datelist.length; j++) {
						if (this.datelist[j].date == date) {
							// console.log(this.datelist[j])this.$forceUpdate()
							userName = this.datelist[j].userName
						}

					}
					this.days.push({
						//这里我只拿了我要的几个数据,你可以根据自己需要处理 ,lunarCalendar 数据很全
						userName,
						gregorian: i,
						cYear: lunarCalendar.cYear,
						cMonth: lunarCalendar.cMonth,
						cDay: lunarCalendar.cDay,
						IDayCn: lunarCalendar.IDayCn, //初几等
						IMonthCn: lunarCalendar.IMonthCn, //正月等
						lDay: lunarCalendar.lDay, //农历日号
						lMonth: lunarCalendar.lMonth //农历月号
					})
					// console.log(this.days)
					this.$forceUpdate()
				}
			},
			dateTransition(month, day) {
				month = month >= 10 ? month : '0' + month;
				day = day >= 10 ? day : '0' + day;
				return [month, day].join('');
			},
			chooseYears(state) { // 改变年份
				this.year += state
				this.today = 1
				this.getdate()
				// this.getDays()
			},
			chooseMonth(state) { // 改变月份
				this.month += state
				this.today = 1
				if (this.month < 1) {
					this.month = 12
					this.chooseYears(-1)
				} else if (this.month > 12) {
					this.month = 1
					this.chooseYears(1)
				} else {
					this.getdate()
					// this.getDays()
				}
			},
			//这里是我要的数据处理, 你用的时候可以根据自己需要做更改
			chooseThisDay(days) { // 选择某天
				if (days.gregorian > 0) {
					this.today = days.gregorian
				}
				let arr = this.dateTransition(days.lMonth, days.lDay);
				let {
					IDayCn,
					IMonthCn
				} = days
				let data = {
					IDayCn,
					IMonthCn,
					arr
				}
				//把 处理好的数据 抛给父组件(即调用此组件的父组件)
				this.$emit('updateLunar', data);
			}
		},
	};
</script>

<style lang="less" scoped>
	.tablelist .el-select {
		width: 100%;
	}

	.drop .start {
		display: none;

	}

	.drop .uname {
		padding-left: 10px;
		width: calc(100% - 38px);
		margin-right: 0 !important;
		text-align: left !important;
	}

	.drop .stop {
		display: block;
		cursor: pointer;
	}

	.userlist .stop {
		display: none;
	}

	.drop .userli {
		min-width: 80% !important;
		// width: 121px !important;
		width: 80%;
		background: #fff;
		margin: 0 auto;
	}

	.drop {
		// min-width: 160px;
		height: 54px;
	}

	.userlist {
		overflow-y: scroll;
		overflow-x: hidden;
		height: calc(100vh - 130px);
	}

	.uname {

		font-size: 14px;
		padding-left: 15px;
		box-sizing: border-box;
		line-height: 34px;
		color: #4286F5;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.drug img {
		width: 23px;
	}

	.drug {
		width: 38px;
		height: 34px;
		background: #4286F5;
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.userli {
		min-width: 160px;
		height: 34px;
		background: #EFF3FC;
		border: 1px solid #4286F5;
		border-radius: 5px;
		margin-top: 10px;
		display: flex;
		justify-content: space-between;
	}

	.main {
		display: flex;
		height: 100%;
		align-items: stretch;
	}

	.scheduling_left {
		min-width: 200px;
		height: 100%;
		border-right: 1px solid #e9e9e9;
		padding: 20px;
	}

	.calender {
		max-width: 1114px;
		width: 100%;
		// height: 300px;
		padding: 30px;
		// margin: 0 auto;

		.calender_title {
			display: flex;
			width: 100%;
			height: 40px;
			line-height: 40px;
			text-align: center;

			.arrow {
				image {
					width: 22px;
				}

				// width: 50px;
				// height: 100%;
			}

			.data {
				font-size: 24px;
				color: #000000;
				margin: 0 19px;
			}
		}

		.calender_content {
			max-width: 1114px;
			width: 100%;
			// height: 250px;
			margin-top: 19px;

			.row {
				max-width: 1114px;
				width: 100%;
				display: flex;
				justify-content: space-between;
				margin: 0;
			}

			.title {
				height: 40px;
				line-height: 40px;

				span {
					width: calc(100% / 7);
					text-align: center;
					color: #000;
					background: #f8f8f8;
					font-size: 16px;
					border: .5px solid #D2D2D2;
				}
			}

			.content {
				-webkit-box-pack: start;
				-ms-flex-pack: start;
				justify-content: flex-start;
				-ms-flex-wrap: wrap;
				flex-wrap: wrap;

				.day {
					width: calc(100% / 7);
					text-align: center;
					border: .5px solid #D2D2D2;
					// width: 159px;
					height: 125px;
					color: #000000;

					p {
						font-size: 27px;
						color: #000000;
						text-align: right;
						margin-right: 25px;
						line-height: 27px;
						margin-top: 15px;
						margin-bottom: 0;
					}

					span {
						font-size: 14px;
						color: #AAAAAA;
						text-align: right;
						margin-right: 25px;
						display: block;
					}
				}

				.prevDay {
					color: #999999;
					// background-color: #eee;
					width: calc(100% / 7);
					height: 60px;
					line-height: 60px;
					text-align: center;
					border: .5px solid #D2D2D2;
					width: 159px;
					height: 125px;
				}
			}
		}
	}
</style>
